package java_0220.leetcode;

/**
 * 判断子树问题
 */
public class Num572_ChildTree {
    /**
     * 传入两棵树root和subRoot就能判断出subRoot是否是root的子树
     * @param root
     * @param subRoot
     * @return
     */
    public boolean isSubtree(TreeNode root, TreeNode subRoot) {
        if (root == null && subRoot == null) {
            return true;
        }
        if (root == null || subRoot == null) {
            return false;
        }
        //如果root==subRoot或者左树和subRoot是否相同或者右树包含，则存在
        return isSameTree(root,subRoot)||isSubtree(root.left,subRoot)||isSubtree(root.right,subRoot);
    }
    public boolean isSameTree(TreeNode p, TreeNode q) {
        if(p==null&&q==null){
            return true;
        }
        if(p==null||q==null){
            return false;
        }
        if(p.val!=q.val){//两棵树根节点的值不相等
            return false;
        }
        //此时两个根节点值相等，再判断子树
        return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
//        return p.val==q.val&& isSameTree(p.left, q.left) && isSameTree(p.right, q.right);//上面几行的简写

    }
}
